package ca.ualberta.cs.CLRServer.Interface;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JOptionPane;

import ca.ualberta.cs.CLRDB.AnnotationDatabase;
import ca.ualberta.cs.CLRDB.DatabaseController;

import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;
import uk.ac.liv.c3connector.AnnotationModelSerialiser;
import uk.ac.liv.c3connector.JDomAnnotationModelSerialiser;

public class ServerInterface {
    
	public static AnnotationModelSerialiser ams = new JDomAnnotationModelSerialiser();
	public static DatabaseController db;// = new AnnotationDatabase();
	
	public static int port = 8888;
	public static String baseUriPrefix = "http://localhost";
	
	public static void runServer(int port, char dbToUse){
		db = new DatabaseController(dbToUse); 
//		final String baseUri = "http://localhost:8888/"; //8080 is in use in hypatia
		
		/*if(dbToUse == 'e' || dbToUse == 'E')
			port = 8880; // for the first experiment
*/		
		final String baseUri = baseUriPrefix + ":"+ String.valueOf(port)+"/";
		System.out.println("address:"+baseUri);
		final Map<String, String> initParams = new HashMap<String, String>();

		initParams.put("com.sun.jersey.config.property.packages","ca.ualberta.cs.CLRServer.resources"); 
		
		SelectorThread threadSelector;
		try {
			threadSelector = GrizzlyWebContainerFactory.create(
					baseUri, initParams);
			
			System.out.println("Hi!");
			System.out.println("Server started...");
			System.out.println("Hit enter to stop server...");
			System.in.read();
			
			threadSelector.stopEndpoint();

		} catch (IllegalArgumentException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
		}
		//System.exit(0);

	}
	
     public static void main(String[] args) throws IOException {
    	 char dbToUse = 's';
    	 ServerInterface.baseUriPrefix = "http://hypatia.cs.ualberta.ca";
//    	 dbToUse = 'e';
    	 dbToUse = 'h';
    	 
    	 try{
    		 ServerInterface.port = Integer.parseInt(args[0]);
    	 }catch(Exception e){
    		 System.out.println("Enter a valid and free port number as the argument to main");
    		 if(dbToUse == 'e' || dbToUse == 'h')
    			 return;
    	 }
         ServerInterface.runServer(port, dbToUse);
     }    
}
